import {Scope} from 'lib/scopeFactory'
import {coreApi} from '../apis/core-util'
import $ from 'jquery'
import DateRangeStore from '../common/DateRangeStore.es6'
import moment from 'moment'
import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import format from 'lib/util/format'

export default class RootScope extends Scope {
  constructor () {
    super();
    this.$state = {
      versions: [],
      channels: [],
      comparerDisplayText: null,
      chart0: {
        loading: true
      },
      grid:{
        loading:true
      },
      duration: () => moment.duration(DateRangeStore.getValue().spanTime),
      dayTypeState: 'daily',
      filterList: [],
      chart0Key: null
    };

    this.recalcChar0Key();

    this.versions = coreApi({
      urlName:'basicinfo/appversion'
    });
    this.channels = coreApi({
      urlName: 'basicinfo/appChannel'
    });
    this.chart0Api = coreApi({
      segment: 'useranalysis',
      urlName: 'useranalysis/useradded',
      timeUnit: () => this.$state.dayTypeState,
      appVersionId: () => {
        let target = _.find(this.$state.filterList, item => item.type === 'version');

        return target ? target.value : undefined;
      },
      channel: () => {
        let target = _.find(this.$state.filterList, item => item.type === 'channel');

        return target ? target.value : undefined;
      }
    }, DateRangeStore.getValue);
    this.chart0Comparer = coreApi({
      urlName: 'useranalysis/useradded',
      timeUnit: () => this.$state.dayTypeState,
      appVersionId: () => {
        let target = _.find(this.$state.filterList, item => item.type === 'version');

        return target ? target.value : undefined;
      },
      channel: () => {
        let target = _.find(this.$state.filterList, item => item.type === 'channel');

        return target ? target.value : undefined;
      }
    });
  }

  convertData(json) {
    return {
      id: 0,
      name: DateRangeStore.getDisplayText(),
      data: _.map(json, (item) => {
        return {
          x: item.startTime,
          y: item.val,
          customData: {
            y: {
              label: '新增用户',
              fmtVal: item.val
            },
            startTime: item.startTime,
            endTime: item.endTime
          }
        };
      })
    };
  } // convertData

  $load_data () {
    let version = _.find(this.$state.filterList, item => item.type === 'version');
    this.$state.versionFilter = version ? version.value : null;

    let target = _.find(this.$state.filterList, item => item.type === 'channel');
    this.$state.channelFilter = target ? target.value : null;

    this.chart0Api.fetch().done((json) => {
      this.recalcChar0Key();

      let reversedJson = _.filter(json, item => true).reverse();
      this.$state.grid = {
        data: _.filter(reversedJson, (value, index) => index < 10),
        showMore: () => {
          let deferred = $.Deferred();
          setTimeout(() => {
            let list = _.filter(this.$state.grid._data, (value, i) => i < 10);
            this.$state.grid._data = _.filter(this.$state.grid._data, (value, i) => i >= 10);

            deferred.resolve({
              data: list,
              hasMore: this.$state.grid._data.length > 0
            });
          }, 300);
          return deferred.promise();
        },
        _data: _.filter(reversedJson, (value, i) => i >= 10),
        _originalData: reversedJson
      };
      this.$state.grid.hasMore = this.$state.grid._data.length > 0;

      this.$state.chart0 = {
        data: {
          yAxis:{
            labels:{
              formatter:function(){
                return format.integer(this.value)
              }
            },
            tickPositioner: function() {
              let positions = [0];
              if (this.dataMax === 0) {
                return positions;
              }

              let maxValue = (this.dataMax % 2) === 1
                               ? (this.dataMax + 1)
                               : this.dataMax;
              let increment = maxValue / 2;

              for (let i = 1; i * increment <= maxValue; i++) {
                  positions.push(i * increment);
              }
              return positions;
            },
            maxPadding:0
          },
          'series': [this.convertData(json)],
          _dataSource:json
        }
      };

      dispatcher.dispatch({
        $type: 'reset_date_comparer'
      });

      this.emit();
    }).fail((err) => {
      console.log(err);
    });
  }

  $filter_check (payload) {
    let targetItem = _.find(this.$state.filterList, item => item.type === payload.filterType);
    if(targetItem) {
      _.extend(targetItem, payload.target);
    } else {
      this.$state.filterList.push(_.extend({type: payload.filterType}, payload.target));
    }

    this.emit();
  }

  $day_type_changed (payload) {
    this.$state.dayTypeState = payload.newType;
    this.$load_data();
  }

  $settime(payload){
    this.$state.dayTypeState = 'daily';
    this.$load_data();
  }

  $load() {
    this.versions.fetch().done((json) => {
      this.$state.versions = json.result;
      this.emit();
    }).fail((err) => {
      console.log(err);
    });

    this.channels.fetch().done((json) => {
      this.$state.channels = json.result;
      this.emit();
    }).fail((err) => {
      console.log(err);
    });

    this.$load_data();
  }

  $compare_date_range(payload) {
    this.$state.comparerDisplayText = payload.data.displayText;
    this.chart0Comparer.fetch((ajaxOptions) => {
      _.extend(ajaxOptions.data, {
        spanTime: payload.data.spanTime,
        endTime: payload.data.endTime
      });
      return ajaxOptions;
    }).done((json) => {
      let spanTime = this.$state.chart0.data.series[0].data[0].x - json[0].startTime;

      let series1 = {
        id: 2,
        name: payload.data.displayText,
        data: _.map(json, (item) => {
          return {
            x: item.startTime + spanTime,
            y: item.val,
            customData: {
              y: {
                label: '新增用户',
                fmtVal: item.val
              },
              startTime: item.startTime,
              endTime: item.endTime
            }
          };
        })
      };
      this.$state.chart0.data.series = [
        this.convertData(this.$state.chart0.data._dataSource),
        series1
      ];
      this.emit();
    });
  }

  recalcChar0Key() {
    this.$state.chart0Key = new Date().getTime();
  }

  $remove_filter(payload) {
    this.$state.filterList = _.filter(this.$state.filterList, item => item.type !== payload.target.type);

    this.emit();
  }
}
